<!-- canvas 画笔 -->
<script lang="ts" setup>
import type { Canvas, CanvasContext } from '@tarojs/taro'
import {
  nextTick,
  useReady,
  createSelectorQuery,
  getWindowInfo,
  canvasToTempFilePath,
} from '@tarojs/taro'
import { ref } from 'vue'

import usePage from '@/hooks/usePage'

const { eventChannel } = usePage()

let startX = 0
let startY = 0
let currentX = 0
let currentY = 0

let canvas: Canvas
let ctx: CanvasContext
let dpr: number

const canvasStyle = ref({
  width: '100px',
  height: '100px',
})

useReady(() => {
  nextTick(() => {
    createSelectorQuery()
      .select('#canvas')
      .fields(
        {
          node: true,
          size: true,
        },
        function (res) {
          console.log('🚀 -- nextTick -- res', res)

          const windowInfo = getWindowInfo()

          const width = windowInfo.windowWidth
          const height = windowInfo.windowHeight
          dpr = wx.getSystemInfoSync().pixelRatio
          canvas = res.node as Canvas
          ctx = canvas.getContext('2d') as CanvasContext

          canvas.width = width * dpr
          canvas.height = height * dpr

          canvasStyle.value = {
            width: width + 'px',
            height: height + 'px',
          }

          setBrush()
        },
      )
      .exec()
  })
})

function setBrush() {
  ctx.lineWidth = 1 * dpr
  ctx.strokeStyle = 'red'
}

function touchstart(e) {
  let touch = e.changedTouches[0]
  startX = touch.x * dpr
  startY = touch.y * dpr
  ctx.moveTo(startX, startY)
}
function touchmove(e) {
  let touch = e.changedTouches[0]
  currentX = touch.x * dpr
  currentY = touch.y * dpr

  ctx.lineTo(currentX, currentY)

  ctx.stroke()
}
function touchend() {}

function onSave() {
  // canvas.createImageData()
  // console.log(ctx)
  // ctx.draw(true, () => {

  // })
  // console.log(getCurrentInstance())
  canvasToTempFilePath({
    x: 0,
    y: 0,
    width: canvas.width,
    height: canvas.height,
    destWidth: canvas.width,
    destHeight: canvas.height,
    // canvasId: 'canvas',
    canvas: canvas as any,
    success(res) {
      eventChannel.emit('acceptDataFromOpenedPage', res.tempFilePath)
    },
  })
}

function onClear() {
  canvas.width = canvas.width
  canvas.height = canvas.height
  setBrush()
}
</script>

<template>
  <div class="DrawPopup">
    <canvas
      disable-scroll="false"
      type="2d"
      id="canvas"
      :style="canvasStyle"
      @touchstart="touchstart"
      @touchmove="touchmove"
      @touchend="touchend"
    ></canvas>
    <button @click="onSave" class="save-btn">保存</button>
    <button @click="onClear" class="clear-btn">清除</button>
  </div>
</template>

<style lang="scss">
.DrawPopup {
  // background-color: #ddd;

  .save-btn {
    position: absolute;
    left: 0;
    bottom: 0;
  }

  .clear-btn {
    position: absolute;
    right: 0;
    bottom: 0;
  }
}
</style>
